
package com.javaleague.administracion;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import com.javaleague.Constantes;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import com.javaleague.sesionUsuario.Usuario;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.javaleague.informacion.ErrorGeneral;
import com.javaleague.informacion.InformacionGeneral;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author TaixMiguel
 */
public class Admin extends HttpServlet {
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
        if ( request.getParameter("infoDoc") != null )
            descargarArchivo(request, response, 0);
        else if ( request.getParameter("erroDoc") != null )
            descargarArchivo(request, response, 1);
            
        
        else if ( request.getParameter("user") != null && request.getParameter("pass") != null ) {
            String userR =  request.getParameter("user");
            String passR = request.getParameter("pass");
            String userD =  com.javaleague.DatosImportantes.Admin.USER;                        
            String passD = com.javaleague.DatosImportantes.Admin.PASS;
            
            if ( userR.equals(userD) && passR.equals(passD) )
                abrirPuerta(request, response);
            else
                sacarPuerta(request, response);
        } else
            sacarPuerta(request, response);
    }
    
    private void abrirPuerta(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = null;
        
        try{    
            out = response.getWriter();
            out.println( getEsqueletoUp() );
            out.println("<a href='" + Constantes.Rutas.PATCH + "/admin?infoDoc' style='position:relative;width:10%;heigth:5%;margin:47.5%0%47.5%40%;background-color:white;'>Informaci&oacute;n</a>");
            out.println("<a href='" + Constantes.Rutas.PATCH + "/admin?erroDoc' style='position:relative;width:10%;heigth:5%;margin:47.5%40%47.5%0%;background-color:white;'>Errores</a>");
            out.println( getEsqueletoDown() );
        }catch (Exception ex){
            ErrorGeneral.guardarLog(Object.class.getName(), Constantes.Informacion.ErrorMensajes.Exception, ex);
        } finally {
            out.close();
        }
    }
    
    private void descargarArchivo(HttpServletRequest request, HttpServletResponse response, int archivo) {
        DataInputStream entrada = null;
        
        PrintWriter out = null;        
        FileInputStream fstream = null;                
        String linea;                
        try {
            switch (archivo) {
                case 0:
                    fstream = new FileInputStream( Constantes.Rutas.INFOR_GENERAL_LOGS );
                    response.setHeader("Content-Disposition","attachment; filename=\""+ Constantes.Rutas.NAME_INFOR_GENERAL_LOGS + "\"");
                    break;
                case 1:
                    fstream = new FileInputStream( Constantes.Rutas.ERROR_GENERAL_LOGS );
                    response.setHeader("Content-Disposition","attachment; filename=\""+ Constantes.Rutas.NAME_ERROR_GENERAL_LOGS + "\"");
                    break;
            }
            response.setContentType("text/x-csv; charset=windows-1252");
            out = response.getWriter();
            entrada = new DataInputStream(fstream);
            BufferedReader buffer = new BufferedReader(new InputStreamReader(entrada));

            while ((linea = buffer.readLine()) != null)
                out.write(linea + "\r\n");
            out.close();
        } catch (IOException ex) {
            Logger.getLogger(Admin.class.getName()).log(Level.SEVERE, null, ex);
        }   
    }
    
    private void sacarPuerta(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession(true);
        Usuario user = (Usuario)session.getAttribute("usuario");
        if (user == null)
            InformacionGeneral.guardarLog(Object.class.getName(), "He intentado acceder al panel administrativo", "Anonimus", request.getRemoteAddr());
        else        
            InformacionGeneral.guardarLog(Object.class.getName(), "He intentado acceder al panel administrativo", user.getNombre(), request.getRemoteAddr());
        try {
            response.sendError(403, "Error Message");
        } catch (IOException ex) {
            ErrorGeneral.guardarLog(Object.class.getName(), "No se ha podido imprimir el mensaje de abrir la puerta", ex);
        }
    }
    
    private String getEsqueletoUp() {
        String source = "";
        
        source += "<!DOCTYPE html>\n";
        source += "<html>\n";
        source += "<head>\n";
        source += "\t<title>Administracion</title>\n";
        source += "\t<link href='"+Constantes.Rutas.PATCH+"css/images/favicon.ico' rel='shortcut icon' />\n";
        source += "\t<style>html{background-image: url('"+Constantes.Rutas.PATCH+"css/images/1d4159.png');}</style>\n";
        source += "</head>\n";
        source += "<body>\n";
        
        return source;
    }
    
    private String getEsqueletoDown() {        
        String source = "";
        
        source += "</body>\n";
        source += "</html>\n";
        
        return source;
    }
    
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
}